package com.xyz.keshe;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.xyz.keshe.adapter.NewsAdapter;
import com.xyz.keshe.adapter.NewsManageAdapter;
import com.xyz.keshe.dao.CategoryDao;
import com.xyz.keshe.dao.NewsDao;
import com.xyz.keshe.model.Category;
import com.xyz.keshe.model.News;

import java.util.ArrayList;
import java.util.List;

public class NewsManageActivity extends AppCompatActivity {

    private ListView lvNews;
    private Button btnAdd;
    private Button btnBack;

    private NewsDao newsDao;
    private CategoryDao categoryDao;
    private List<News> newsList;
    private List<Category> categoryList;
    private NewsManageAdapter newsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_manage);

        // 初始化视图
        lvNews = findViewById(R.id.lv_news);
        btnAdd = findViewById(R.id.btn_add);
        btnBack = findViewById(R.id.btn_back);

        // 初始化DAO
        newsDao = new NewsDao(this);
        categoryDao = new CategoryDao(this);

        // 加载数据
        loadData();

        // 设置添加按钮点击事件
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAddDialog();
            }
        });

        // 设置返回按钮点击事件
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void loadData() {
        // 获取所有新闻
        newsList = newsDao.getAllNews();
        newsAdapter = new NewsManageAdapter(this, newsList, new NewsManageAdapter.OnNewsActionListener() {
            @Override
            public void onView(News news) {
                // 查看新闻详情（管理员视图）
                Intent intent = new Intent(NewsManageActivity.this, NewsAdminDetailActivity.class);
                intent.putExtra("news_id", news.getId());
                startActivityForResult(intent, 1001);
            }

            @Override
            public void onEdit(News news) {
                // 编辑新闻
                showEditDialog(news);
            }

            @Override
            public void onDelete(News news) {
                // 删除新闻
                showDeleteDialog(news);
            }
        });
        lvNews.setAdapter(newsAdapter);

        // 获取所有栏目
        categoryList = categoryDao.getAllCategories();
    }

    private void showAddDialog() {
        // 检查是否有栏目
        if (categoryList.isEmpty()) {
            Toast.makeText(this, "请先添加栏目", Toast.LENGTH_SHORT).show();
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_news_edit, null);
        builder.setView(view);
        builder.setTitle("添加新闻");

        final EditText etTitle = view.findViewById(R.id.et_title);
        final EditText etContent = view.findViewById(R.id.et_content);
        final EditText etAuthor = view.findViewById(R.id.et_author);
        final Spinner spCategory = view.findViewById(R.id.sp_category);

        // 设置栏目下拉列表
        List<String> categoryNames = new ArrayList<>();
        for (Category category : categoryList) {
            categoryNames.add(category.getName());
        }
        ArrayAdapter<String> categoryAdapter = new ArrayAdapter<>(this, 
                android.R.layout.simple_spinner_item, categoryNames);
        categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spCategory.setAdapter(categoryAdapter);

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String title = etTitle.getText().toString().trim();
                String content = etContent.getText().toString().trim();
                String author = etAuthor.getText().toString().trim();
                int position = spCategory.getSelectedItemPosition();

                if (TextUtils.isEmpty(title)) {
                    Toast.makeText(NewsManageActivity.this, "标题不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(content)) {
                    Toast.makeText(NewsManageActivity.this, "内容不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                News news = new News();
                news.setTitle(title);
                news.setContent(content);
                news.setAuthor(author);
                news.setCategoryId(categoryList.get(position).getId());

                long id = newsDao.addNews(news);
                if (id > 0) {
                    Toast.makeText(NewsManageActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                    loadData();
                } else {
                    Toast.makeText(NewsManageActivity.this, "添加失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        builder.setNegativeButton("取消", null);
        builder.show();
    }



    private void showEditDialog(final News news) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_news_edit, null);
        builder.setView(view);
        builder.setTitle("编辑新闻");

        final EditText etTitle = view.findViewById(R.id.et_title);
        final EditText etContent = view.findViewById(R.id.et_content);
        final EditText etAuthor = view.findViewById(R.id.et_author);
        final Spinner spCategory = view.findViewById(R.id.sp_category);

        // 设置现有数据
        etTitle.setText(news.getTitle());
        etContent.setText(news.getContent());
        etAuthor.setText(news.getAuthor());

        // 设置栏目下拉列表
        List<String> categoryNames = new ArrayList<>();
        int selectedPosition = 0;
        for (int i = 0; i < categoryList.size(); i++) {
            Category category = categoryList.get(i);
            categoryNames.add(category.getName());
            if (category.getId() == news.getCategoryId()) {
                selectedPosition = i;
            }
        }
        ArrayAdapter<String> categoryAdapter = new ArrayAdapter<>(this, 
                android.R.layout.simple_spinner_item, categoryNames);
        categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spCategory.setAdapter(categoryAdapter);
        spCategory.setSelection(selectedPosition);

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String title = etTitle.getText().toString().trim();
                String content = etContent.getText().toString().trim();
                String author = etAuthor.getText().toString().trim();
                int position = spCategory.getSelectedItemPosition();

                if (TextUtils.isEmpty(title)) {
                    Toast.makeText(NewsManageActivity.this, "标题不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(content)) {
                    Toast.makeText(NewsManageActivity.this, "内容不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                news.setTitle(title);
                news.setContent(content);
                news.setAuthor(author);
                news.setCategoryId(categoryList.get(position).getId());

                int count = newsDao.updateNews(news);
                if (count > 0) {
                    Toast.makeText(NewsManageActivity.this, "更新成功", Toast.LENGTH_SHORT).show();
                    loadData();
                } else {
                    Toast.makeText(NewsManageActivity.this, "更新失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        builder.setNegativeButton("取消", null);
        builder.show();
    }

    private void showDeleteDialog(final News news) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("确认删除");
        builder.setMessage("确定要删除新闻 \"" + news.getTitle() + "\" 吗？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                newsDao.deleteNews(news.getId());
                Toast.makeText(NewsManageActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                loadData();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == 1001 && resultCode == RESULT_OK && data != null) {
            String action = data.getStringExtra("action");
            if ("edit".equals(action)) {
                int newsId = data.getIntExtra("news_id", 0);
                if (newsId > 0) {
                    // 找到对应的新闻并显示编辑对话框
                    for (News news : newsList) {
                        if (news.getId() == newsId) {
                            showEditDialog(news);
                            break;
                        }
                    }
                }
            }
        }
    }
} 